import sys
import time
import openpyxl
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QMessageBox
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QFileDialog, 
                           QVBoxLayout, QWidget, QDialog, QLabel, QDialogButtonBox,
                           QTextEdit)
from PyQt6.QtCore import Qt, QTimer
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 全局变量，用于存储双击元素的XPATH和对应的值
xpath_list = []
value_list = []


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        start_button = QPushButton('Start')
        start_button.clicked.connect(self.start_process)

        layout.addWidget(start_button)
        self.setLayout(layout)

        self.setWindowTitle('My App')
        self.show()

    def start_process(self):
        # 打开Excel文件并读取URL
        file_name, _ = QFileDialog.getOpenFileName(
            self, "选择文件", "", "Text Files (*.txt)"
        )
        urls=[]
        if not file_name:
            return
        try:
            # 读取文本文件
            with open(file_name, 'r', encoding='utf-8') as file:
                urls = [line.strip() for line in file if line.strip()]
        except  Exception as e:
            print(f"Error reading file: {e}")
            return
        # 启动Chrome浏览器驱动
        driver = webdriver.Chrome()
 
        driver.get(urls[0])
        # 这里可以添加更多监控网页的逻辑，比如等待页面加载完成等
        time.sleep(2)
        self.monitor_webpage(driver)

        driver.quit()

    def monitor_webpage(self, driver):
        def on_element_double_clicked(element):
            xpath = self.get_xpath(element)
            xpath_list.append(xpath)
            msg_box = QMessageBox()
            msg_box.setWindowTitle("确认操作")
            msg_box.setText("确认获取元素值并继续吗？")
            msg_box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
            result = msg_box.exec()
            if result == QMessageBox.StandardButton.Yes:
                value = element.text
                value_list.append(value)
            else:
                pass

        elements = driver.find_elements(By.XPATH, "//*")  # 简单示例，可根据实际情况调整查找元素的XPATH
        for element in elements:
            detector = ElementDoubleClickDetector(element)
            detector.double_clicked.connect(self.on_element_double_clicked)

        # 所有元素双击完成后，生成流程（这里简单示例，实际可能更复杂）
        if len(xpath_list) == len(elements):
            self.generate_process()

    def get_xpath(self, element):
        try:
            return element.get_attribute('xpath')
        except:
            return ''

    def generate_process(self):
        # 执行流程，将获取的元素值写入另一个Excel
        output_workbook = openpyxl.Workbook()
        output_sheet = output_workbook.active

        for xpath, value in zip(xpath_list, value_list):
            output_sheet.append([xpath, value])

        output_workbook.save('output.xlsx')  # 替换为你的输出Excel文件名


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())